<template>
  <div class="transfer-form-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">新增调拨单</h1>
    </div>

    <!-- 基础信息区域 -->
    <div class="form-section">
      <div class="section-header">
        <h2 class="section-title">基础信息</h2>
      </div>

      <el-form ref="basicFormRef" :model="basicForm" :rules="basicRules" label-width="120px" class="basic-form">
        <div class="form-row">
          <!-- 左列 -->
          <div class="form-column">
            <el-form-item label="调拨单号" prop="movingCode" required>
              <el-input v-model="basicForm.movingCode" placeholder="自动获取系统编号" disabled class="form-input" />
            </el-form-item>

            <el-form-item label="调拨申请日期" prop="createTime" required>
              <el-date-picker v-model="basicForm.createTime" type="datetime" placeholder="请选择"
                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DDTHH:mm:ss.SSS[Z]" class="form-input" />
            </el-form-item>

            <el-form-item label="调入仓库" prop="original_Position" required>
              <div class="input-with-button">
                <el-select v-model="basicForm.original_Position" placeholder="请选择" class="form-input warehouse-select"
                  clearable>
                  <el-option v-for="item in Warehousement" :label="item.warehouse_Name" :value="item.id"
                    :key="`in-${item.id}`" />
                </el-select>
                <el-button type="success" size="small" class="set-btn">设置</el-button>
              </div>
            </el-form-item>

            <el-form-item label="备注" prop="notes">
              <el-input v-model="basicForm.notes" type="textarea" :rows="3" placeholder="请输入" class="form-input" />
            </el-form-item>
          </div>

          <!-- 右列 -->
          <div class="form-column">
            <el-form-item label="调拨类型" prop="allotWarehouseType">
              <el-select v-model="basicForm.allotWarehouseType" placeholder="请选择" class="form-input" clearable>
                <el-option label="货品调拨" value="货品调拨" />
                <el-option label="设备调拨" value="设备调拨" />
                <el-option label="其他调拨" value="其他调拨" />
              </el-select>
            </el-form-item>

            <el-form-item label="调出仓库" prop="original_Warehouse" required>
              <div class="input-with-button">
                <el-select v-model="basicForm.original_Warehouse" placeholder="请选择" class="form-input warehouse-select"
                  clearable @change="handleWarehouseChange">
                  <el-option v-for="item in Warehousement" :label="item.warehouse_Name" :value="item.id"
                    :key="`out-${item.id}`" />
                </el-select>
                <el-button type="success" size="small" class="set-btn">设置</el-button>
              </div>
            </el-form-item>

            <el-form-item label="经办人" prop="reviewer">
              <div class="input-with-button">
                <el-select v-model="basicForm.reviewer" placeholder="请选择" class="form-input" clearable>
                  <el-option label="吴维昊" value="吴维昊" />
                  <el-option label="王雨龙" value="王雨龙" />
                  <el-option label="张可欣" value="张可欣" />
                  <el-option label="赵姝雅" value="赵姝雅" />
                  <el-option label="段栋兴" value="段栋兴" />
                </el-select>
                <el-button size="small" class="more-btn">...</el-button>
              </div>
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>

    <!-- 调拨明细区域 -->
    <div class="form-section">
      <div class="section-header">
        <h2 class="section-title">调拨明细</h2>
        <div class="section-actions">
          <el-button type="success" @click="addTransferItem" class="action-btn">
            <el-icon>
              <Plus />
            </el-icon>
            添加
          </el-button>
          <el-button @click="removeSelectedItems" class="action-btn remove-btn">
            <el-icon>
              <Delete />
            </el-icon>
            移除
          </el-button>
        </div>
      </div>

      <div class="table-container">
        <el-table ref="transferTableRef" :data="transferItems" @selection-change="handleSelectionChange"
          class="transfer-table">
          <el-table-column type="selection" width="55" :selectable="() => true">
            <template #header>
              <el-checkbox v-model="isAllSelected" :indeterminate="isIndeterminate" />
            </template>
          </el-table-column>
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="productName" label="货品名称" width="150" />
          <el-table-column prop="productCode" label="货品编号" width="150" />
          <el-table-column prop="specification" label="规格型号" width="150" />
          <el-table-column prop="unit" label="单位" width="120" />
          <el-table-column prop="productType" label="货品类型" width="120" />
          <el-table-column prop="outboundStock" label="调出仓库当前库存" width="150" />
          <el-table-column prop="inboundStock" label="调入仓库当前库存" width="150" />
          <el-table-column prop="transferQuantity" label="调拨数量" width="150">
            <template #default="scope">
              <el-input v-model.number="scope.row.transferQuantity" placeholder="请输入"
                @input="calculateAmount(scope.row)" @focus="handleProductFocus(scope.row)" class="quantity-input" />
            </template>
          </el-table-column>
          <el-table-column prop="unitPrice" label="入库单价" width="120">
            <template #default="scope">
              <el-input v-model.number="scope.row.unitPrice" placeholder="0.00" class="price-input" />
            </template>
          </el-table-column>
          <el-table-column prop="transferAmount" label="调拨金额" width="120">
            <template #default="scope">
              <span class="amount-display">{{ scope.row.transferAmount ? scope.row.transferAmount.toFixed(2) : '0.00'
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button type="text" @click="removeItem(scope.$index)" class="remove-link">
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 合计信息 -->
        <div class="summary-section">
          <div class="summary-item">
            <span class="summary-label">调拨种类:</span>
            <span class="summary-value">{{ transferItems.length }}</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">调拨数量:</span>
            <span class="summary-value">{{ totalQuantity }}</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">调拨金额:</span>
            <span class="summary-value">¥{{ totalAmount.toFixed(2) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <el-button @click="goBack" class="cancel-btn">取消</el-button>
      <el-button type="primary" @click="submitForm" class="submit-btn">提交</el-button>
    </div>

    <!-- 货品选择弹窗 -->
    <el-dialog v-model="productDialogVisible" title="选择货品" width="800px" class="product-dialog">
      <div class="dialog-content">
        <el-table :data="availableProducts" @selection-change="handleProductSelection" class="product-table"
          ref="productTableRef">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="product_Name" label="货品名称" />
          <el-table-column prop="product_Number" label="货品编号" />
          <el-table-column prop="specifications" label="规格型号" />
          <el-table-column prop="unit_Name" label="单位" />
          <el-table-column prop="price" label="入库单价" />
          <el-table-column prop="warehouse_InOrOutCount" label="当前库存" />
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="productDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmProductSelection">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { statementRed } from '@/http/axiosHelper'

const router = useRouter()

// 表格引用
const transferTableRef = ref()
const productTableRef = ref()

// 定义类型接口
interface TransferItem {
  productName: string
  productCode: string
  specification: string
  unit: string
  productType: string
  outboundStock: number
  inboundStock: number
  transferQuantity: number
  unitPrice: number
  transferAmount: number
  id?: number // 产品ID字段
}

// 基础表单数据
const basicForm = reactive({
  "tableType": 2,
  "movingCode": "",
  "allotWarehouseType": "",
  "createTime": "",
  "original_Warehouse": null as number | null, // 改为number类型存储仓库ID
  "original_Position": null as number | null,  // 改为number类型存储仓库ID
  "reviewer": "",
  "notes": "",
  "allotCount": 0,
  "state": "待审批",
  "batch": "",
  "product_Id": 0,
  "createUse": 1039
})

const page = reactive({
  PageIndex: 1,
  PageSize: 15,
  totalCount: 0
})

// 仓库列表数据
const Warehousement = ref<any[]>([])

// 获取仓库列表
const Warehousementdata = () => {
  statementRed.get("/api/Inventory/GetWarehouse").then(res => {
    if (res.data.code === 200) {
      Warehousement.value = res.data.data || []
    } else {
      ElMessage.error('获取仓库列表失败')
    }
  }).catch(error => {
    console.error('获取仓库列表出错:', error)
    ElMessage.error('获取仓库列表失败，请重试')
  })
}

// 基础表单验证规则
const basicRules = {
  createTime: [
    { required: true, message: '请选择调拨申请日期', trigger: 'change' }
  ],
  original_Position: [
    { required: true, message: '请选择入库仓库', trigger: 'change' }
  ],
  original_Warehouse: [
    { required: true, message: '请选择出库仓库', trigger: 'change' }
  ]
}

// 调拨明细数据
const transferItems = ref<TransferItem[]>([])

// 选中的行
const selectedRows = ref<TransferItem[]>([])
const selectedProducts = ref<any[]>([])

// 弹窗控制
const productDialogVisible = ref(false)

// 可用货品数据
const availableProducts = ref([])

// 根据仓库ID获取库存信息
const ProductInventoryTransfer = (Warehouse_ID: number) => {
  statementRed.get("/api/TwoWorkOrder/GetInventoryHandle", {
    params: { Warehouse_ID }
  }).then(res => {
    if (res.data.code === 200) {
      availableProducts.value = res.data.data || []
    } else {
      ElMessage.error(res.data.msg || '获取库存信息失败')
    }
  }).catch(error => {
    console.error('获取库存信息出错:', error)
    ElMessage.error('获取库存信息失败，请重试')
  })
}

// 处理仓库选择变化（现在接收的是仓库ID）
const handleWarehouseChange = (warehouseId: number | null) => {
  if (warehouseId) {
    ProductInventoryTransfer(warehouseId)
  } else {
    availableProducts.value = []
  }
}

// 计算属性
const totalQuantity = computed(() => {
  return transferItems.value.reduce((sum, item) => {
    return sum + (item.transferQuantity || 0)
  }, 0)
})

const totalAmount = computed(() => {
  return transferItems.value.reduce((sum, item) => {
    return sum + (item.transferAmount || 0)
  }, 0)
})

// 判断是否全选
const isAllSelected = computed({
  get: () => {
    return transferItems.value.length > 0 && selectedRows.value.length === transferItems.value.length
  },
  set: (val: boolean) => {
    handleSelectAll(val)
  }
})

// 判断是否部分选中
const isIndeterminate = computed(() => {
  return selectedRows.value.length > 0 && selectedRows.value.length < transferItems.value.length
})

// 方法
const addTransferItem = () => {
  if (!basicForm.original_Warehouse) {
    ElMessage.warning('请先选择调出仓库')
    return
  }
  productDialogVisible.value = true
}

// 全选/取消全选
const handleSelectAll = (val: boolean) => {
  if (val) {
    // 全选
    transferItems.value.forEach(row => {
      transferTableRef.value?.toggleRowSelection(row, true)
    })
  } else {
    // 取消全选
    transferTableRef.value?.clearSelection()
  }
}

const removeSelectedItems = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要移除的货品')
    return
  }

  const indices = selectedRows.value.map(row => transferItems.value.indexOf(row)).sort((a, b) => b - a)
  indices.forEach(index => {
    transferItems.value.splice(index, 1)
  })

  ElMessage.success('移除成功')
  updateTotalAllotCount()
}

const removeItem = (index: number) => {
  transferItems.value.splice(index, 1)
  ElMessage.success('移除成功')
  updateTotalAllotCount()
}

const handleSelectionChange = (selection: TransferItem[]) => {
  selectedRows.value = selection
}

const handleProductSelection = (selection: any[]) => {
  selectedProducts.value = selection
}

const confirmProductSelection = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择货品')
    return
  }

  selectedProducts.value.forEach((product: any) => {
    const newItem: TransferItem = {
      productName: product.product_Name || product.productName,
      productCode: product.product_Number || product.productCode,
      specification: product.specifications || product.specification,
      unit: product.unit_Name || product.unit,
      productType: product.productType || '货品',
      outboundStock: Number(product.warehouse_InOrOutCount) || 0,
      inboundStock: 0,
      transferQuantity: 0,
      unitPrice: Number(product.price) || 0,
      transferAmount: 0,
      id: product.id || product.product_Id
    }
    transferItems.value.push(newItem)
  })

  productDialogVisible.value = false
  ElMessage.success('添加货品成功')
}

const calculateAmount = (item: TransferItem) => {
  const quantity = item.transferQuantity || 0
  const unitPrice = item.unitPrice || 0
  item.transferAmount = quantity * unitPrice
  updateTotalAllotCount()
}

// 更新总调拨数量
const updateTotalAllotCount = () => {
  const totalCount = transferItems.value.reduce((sum, item) => {
    return sum + (item.transferQuantity || 0)
  }, 0)
  basicForm.allotCount = totalCount
}

// 处理商品焦点事件
const handleProductFocus = (item: TransferItem) => {
  if (item.id) {
    basicForm.product_Id = item.id
  }
}

const validateForm = () => {
  // 验证基础信息
  if (!basicForm.original_Position) {
    ElMessage.warning('请选择入库仓库!')
    return false
  }

  if (!basicForm.original_Warehouse) {
    ElMessage.warning('请选择出库仓库!')
    return false
  }

  if (basicForm.original_Warehouse === basicForm.original_Position) {
    ElMessage.warning('入库仓库和出库仓库不能为同一仓库!')
    return false
  }

  // 验证调拨明细
  if (transferItems.value.length === 0) {
    ElMessage.warning('请选择货品!')
    return false
  }

  // 验证数量
  for (let item of transferItems.value) {
    const quantity = item.transferQuantity || 0
    if (quantity <= 0) {
      ElMessage.error('货品数量必须大于0!')
      return false
    }

    // 验证库存是否足够
    if (quantity > item.outboundStock) {
      ElMessage.error(`"${item.productName}" 库存不足，当前库存: ${item.outboundStock}`)
      return false
    }
  }

  return true
}

const submitForm = async () => {
  // 基础验证
  if (!validateForm()) {
    return
  }

  // 检查库存下限（异步确认）
  for (let item of transferItems.value) {
    const quantity = item.transferQuantity || 0
    const outboundStock = item.outboundStock || 0
    const lowerLimit = outboundStock * 0.1 // 假设下限为库存的10%

    if (outboundStock - quantity < lowerLimit) {
      try {
        await ElMessageBox.confirm(
          `"${item.productName}" 当前操作后库存将低于下限,是否继续?`,
          '库存预警',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
      } catch {
        // 用户取消操作
        return
      }
    }
  }

  try {
    // 准备提交数据，确保所有数值类型正确
    const submitData = {
      createInventories: [
        {
          tableType: basicForm.tableType,
          movingCode: basicForm.movingCode,
          allotWarehouseType: basicForm.allotWarehouseType || '货品调拨',
          createTime: basicForm.createTime,
          original_Warehouse: basicForm.original_Warehouse, // 传递整数ID
          original_Position: basicForm.original_Position,   // 传递整数ID
          reviewer: basicForm.reviewer,
          notes: basicForm.notes,
          allotCount: basicForm.allotCount,
          state: basicForm.state,
          batch: basicForm.batch,
          product_Id: basicForm.product_Id,
          createUse: basicForm.createUse,
          // 添加明细数据
          details: transferItems.value.map(item => ({
            productId: item.id,
            productName: item.productName,
            transferQuantity: item.transferQuantity,
            unitPrice: item.unitPrice,
            transferAmount: item.transferAmount
          }))
        }
      ]
    }

    console.log('提交的数据:', submitData)
    const res = await statementRed.post("/api/WorkOrder/CreateInventoryHandle", submitData)

    if (res.data.code === 200) {
      ElMessage.success(res.data.msg || '提交成功')
      goBack()
    } else {
      ElMessage.error(res.data.msg || '提交失败')
    }
  } catch (error: any) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败: ' + (error.response?.data?.msg || error.message))
  }
}

const goBack = () => {
  router.go(-1)
}

// 生成调拨单号
const generateTransferNumber = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  basicForm.movingCode = `DB${year}${month}${day}${random}`
  basicForm.batch = basicForm.movingCode
}

onMounted(() => {
  Warehousementdata()
  generateTransferNumber()
  basicForm.createTime = new Date().toISOString()
  updateTotalAllotCount()
})
</script>

<style scoped>
.transfer-form-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.page-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.page-title {
  font-size: 24px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0;
  text-align: center;
}

.form-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f0f2f5;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
}

.section-actions {
  display: flex;
  gap: 12px;
}

.action-btn {
  border-radius: 8px;
  padding: 8px 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  border: none;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.remove-btn {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
  color: white;
}

.remove-btn:hover {
  background: linear-gradient(135deg, #ee5a52, #d63031);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3);
}

.basic-form {
  width: 100%;
}

.form-row {
  display: flex;
  gap: 40px;
}

.form-column {
  flex: 1;
}

.form-input {
  width: 100%;
}

.warehouse-select {
  min-width: 200px;
  width: 100%;
}

.input-with-button {
  display: flex;
  gap: 8px;
  align-items: center;
  width: 100%;
}

.input-with-button .form-input {
  flex: 1;
  min-width: 0;
}

.set-btn {
  background: linear-gradient(135deg, #28a745, #20c997);
  border: none;
  color: white;
  border-radius: 6px;
  padding: 6px 12px;
  font-size: 12px;
}

.set-btn:hover {
  background: linear-gradient(135deg, #218838, #1e7e34);
  transform: translateY(-1px);
}

.more-btn {
  background: #f8f9fa;
  border: 1px solid #dee2e6;
  color: #6c757d;
  border-radius: 6px;
  padding: 6px 12px;
  font-size: 12px;
}

.more-btn:hover {
  background: #e9ecef;
  border-color: #adb5bd;
  color: #495057;
}

.table-container {
  margin-top: 20px;
}

.transfer-table {
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
}

.transfer-table :deep(.el-table__header-wrapper) {
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
}

.quantity-input,
.price-input {
  width: 100%;
}

.amount-display {
  font-weight: 600;
  color: #67c23a;
}

.remove-link {
  color: #28a745;
  font-weight: 500;
}

.remove-link:hover {
  color: #218838;
  text-decoration: underline;
}

.summary-section {
  display: flex;
  gap: 40px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.summary-label {
  font-weight: 500;
  color: #6c757d;
}

.summary-value {
  font-weight: 600;
  color: #2c3e50;
  font-size: 16px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 32px;
}

.cancel-btn {
  background: #f8f9fa;
  border: 1px solid #dee2e6;
  color: #6c757d;
  border-radius: 8px;
  padding: 12px 24px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background: #e9ecef;
  border-color: #adb5bd;
  color: #495057;
}

.submit-btn {
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
  color: white;
  border-radius: 8px;
  padding: 12px 24px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.submit-btn:hover {
  background: linear-gradient(135deg, #5a6fd8, #6a4190);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.product-dialog {
  border-radius: 16px;
  overflow: hidden;
}

.product-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  padding: 20px;
}

.product-dialog :deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

@media (max-width: 1200px) {
  .transfer-form-container {
    padding: 16px;
  }

  .form-row {
    flex-direction: column;
    gap: 20px;
  }

  .summary-section {
    flex-direction: column;
    gap: 12px;
  }
}

@media (max-width: 768px) {
  .section-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .section-actions {
    width: 100%;
    justify-content: center;
  }

  .form-actions {
    flex-direction: column;
    gap: 12px;
  }

  .cancel-btn,
  .submit-btn {
    width: 100%;
  }
}
</style>
